<template>
  <view>
    <f-navbar title="派单" navbarType="1"> </f-navbar>
    <view class="dispatch">
      <view class="form">
        <u--form
          labelPosition="left"
          :model="form"
          :rules="rules"
		  ref="uForm"
          labelWidth="80"
        >
          <!-- <u-form-item
            required
            class="form-item"
            label="收运公司"
            prop="recyclingCompanyId"
          >
            <LSelect border="none"  v-model="form.recyclingCompanyId" 
				dataKey="companyName" dataValue="id" :localdata="companyList" @change="companySelect">
			</LSelect>
            
          </u-form-item> -->
		  <u-form-item
		    label="收运时间"
		    prop="collectionTime"
		    required
		    class="form-item"
		  >
		  			<picker mode="date" :value="form.collectionTime" @change="collectionTimeChange">
		  			  <view class="box-item">
		  			    <view v-if="form.collectionTime">{{
		  			      formatDate(form.collectionTime, "Y-m-d")
		  			    }}</view>
		  			    <view class="item-text" style="color: #c0c4cc" v-else>请选择</view>
		  			  </view>
		  			</picker>
		  </u-form-item>
          <u-form-item
            required
            label="指派司机"
            prop="driverId"
            class="form-item"
			@click="selectDriver"
          >
            <!-- <LSelect border="none"  v-model="form.driverId"
            	dataKey="name" dataValue="id" :localdata="driverList" >
            </LSelect> -->
			<view class="" style="font-size: 16px;" v-if="form.driverName"> {{form.driverName}}</view>
			<view class="" style="color: #ccc;font-size: 16px;" v-else>请选择</view>
			<!-- <u--input
			  v-model="form.driverName"
			  placeholder="请选择"
			  border="none"
			  readonly
			  disabledColor="#fff"
			></u--input> -->
          </u-form-item>
		 
		  <!-- receive_car_class -->
          <u-form-item required label="车辆类型" prop="vehicleType" class="form-item">
            <LSelect border="none"  v-model="form.vehicleType"
            	 dataKey="dictLabel" dataValue="dictValue" :localdata="receiveCarClassList" @change="vehicleSelect">
            </LSelect>
          </u-form-item>
          <u-form-item required label="指派车辆" prop="receivingVehicleId" class="form-item">
            <LSelect border="none"  v-model="form.receivingVehicleId"
            	dataKey="licensePlateNumber" dataValue="id" :localdata="receivingList">
            </LSelect>
          </u-form-item>
		  <u-form-item required label="中转站" prop="recycleBinId" class="form-item">
		    <LSelect border="none"  v-model="form.recycleBinId"
		    	dataKey="transferStationName" dataValue="id" :localdata="transferAllList">
		    </LSelect>
		  </u-form-item>
		  <u-form-item label="指派收运工" prop="recyclerId" class="form-item">
		    <LSelect border="none"  v-model="form.recyclerId"
		    	dataKey="name" dataValue="id" :localdata="driverList2">
		    </LSelect>
		  </u-form-item>
		  <u-form-item
		    label="重量误差（kg）" prop="weightError" required class="form-item" labelWidth="120" >
		    <u--input
		      v-model="form.weightError"
		      placeholder="请输入"
		      border="none"
		    ></u--input>
		  </u-form-item>
		  <u-form-item label="记录仪" prop="recorderId" class="form-item">
		    <LSelect border="none"  v-model="form.recorderId"
		    	dataKey="name" dataValue="id" :localdata="listAllVehicleTerminal">
		    </LSelect>
		  </u-form-item>
		  <view class=""  v-if="form.orderVoList.length > 1">
			<u-form-item label="订单排序"  class="form-item"> </u-form-item>
			<view class="order-list">
				<view class="item"  v-for="(item, index) in form.orderVoList" :key="index">
					<view class="text">{{ item.orderCode }}</view>
					<view class="text">{{ item.emissionUnitName }}</view>
					<view class="text">
						排序：
						<u--input
						  v-model="item.orderSort"
						  placeholder="请输入"
						  border="none"
						></u--input>
					</view>
				</view>
			</view>
		  </view>
		  
		  <u-form-item label="路线规划" required prop="routingPic" class="form-item" >
			<view style="width:100px;position: relative;"><u-button type="primary" text="点击生成" @click="	createPath()"></u-button></view>
		  </u-form-item>
		  <view class="" ref="map"  id="content2PDF">
		  	<pathPlan  :pathList="pathList" v-if="pathList.origin"></pathPlan>
		  </view>
		  
		  
        </u--form>
      </view>
      <view class="button">
        <view class="button1" @click="render2.myprint">确认</view>
      </view>
    </view>
	
	<!-- 选择司机 -->
	<u-popup :show="driveShow"  mode="center" :round="30" @close="driveShow = false" :safeAreaInsetBottom="false">
		<view class="drive-wrap">
		  <view class="list">
			<view class="item" v-for="(item,index) in driverData" :key="index" @click="driveConfirm(item)">
				<view class="name">{{item.name}}</view>
				<view class="text">状态：
					<view style="color: #ff9900" v-if="item.jobStatus == 1">忙碌</view>
					<view style="color: #19be6b" v-else>闲置</view>
				</view>
				<view class="text">任务数：{{item.taskCount || '0'}}</view>
				<view class="text" style="color: #1890ff;">选择</view>
			</view>
		  </view>
		</view>
	</u-popup>
  
  
  </view>
</template>

<script>
import LSelect from "@/components/LSelect";
import pathPlan from "../component/pathPlan.vue";
import { 
	addLn_receipt_shipment_order,
	user_sign_allList,
	user_oil_charge_standard ,
	category_allList,
	listAllTransfer_station,
	listAllRecycling_company,
	listAll_driver,
	listAll_receiving_vehicle,
	collection_transportation_task,
	dispatch,
	allListDevices,
	selectDriverTaskCount,
	planRoute,
	uploadBase64,
	getVehicleType
	} from "@/api/collection.js";

import html2canvas from 'html2canvas';
export default {
  components: {
    LSelect,
	pathPlan
  },
  data() {
    return {
      form: {
		taskType: 0, //收运订单
		collectionTime:'',
		recyclingCompanyId:'',		driverId:'',
		driverName:'',		vehicleType:'',		receivingVehicleId:'',		recycleBinId:'',		recyclerId:'',
		weightError: null,
		recorderId: null,
		orderVoList: [],
	  },
	  companyList:[], //收运公司列表
		driverList:[], //司机列表
		driverList2:[], //收运工列表
		receivingList:[], // 车辆列表
		transferAllList:[],//中转站
		receiveCarClassList:[],//车辆类型
		listAllVehicleTerminal:[], //记录仪列表
      rules: {
		  recyclingCompanyId: [{ required: true, message: "请选择收运公司", trigger: "blur" }],     
		  driverId: [{ required: true, message: "请选择司机", trigger: "blur" }],           
		  vehicleType: [{ required: true, message: "请选择车辆类型", trigger: "blur" }],        
		  receivingVehicleId: [{ required: true, message: "请选择车辆", trigger: "blur" }],        
		  recycleBinId: [{ required: true, message: "请选择中转站", trigger: "blur" }],        
		  weightError: [{ required: true, message: "请输入重量误差", trigger: "blur" }],  
		  collectionTime: [{ required: true, message: "请选择收运时间", trigger: "blur" }],      
		  // recorderId: [{ required: true, message: "请选择记录仪", trigger: "blur" }],  
		  routingPic: [ { required: true, message: "请点击生成路线规划", trigger: "blur" }],
      },
	  driveShow:false,
	  driverData:[],
	  pathList:{},
    };
  },
  onLoad(option) {
	// console.log(option);
	// console.log(JSON.parse(option.select));
	if (option.select) {
		console.log('option.select',option.select);
		this.form.orderVoList = JSON.parse(option.select).map((item, index) => {
			return {
			  orderId: item.id,
			  orderCode: item.orderCode,
			  orderSort: index + 1,
			  emissionUnitId: item.emissionUnitId,
			  emissionUnitName: item.emissionUnitName,
			};
		});
		// console.log('this.form.orderVoList',this.form.orderVoList);
	}
	//this.form.orderId = option.id
	// this.form.orderCode = option.orderCode
  },
  onShow() {
	if (uni.getStorageSync('token')) {
		this.$store.dispatch("actionGetUserInfo");
		this.form.recyclingCompanyId = this.userInfo.deptId
	}
  	this.getTransferAllList()
	// this.listAllRecycling_company()
	this.getVehicleTypeData()
  },
  methods: {
	// async getData() {
	// 	this.receiveCarClassList = await this.getDictionaryData("receive_car_class");
	// },
	getVehicleTypeData(val) {
	  // 1收运 2运输
	  getVehicleType(1).then((res) => {
		console.log(res.data);
		this.receiveCarClassList = res.data;
	  });
	},
	collectionTimeChange(e) {
      this.form.collectionTime = e.detail.value ;
	  this.form.driverId = null;
	  this.form.driverName = null;
    },
	// 查询所有中转站
	getTransferAllList(){
		listAllTransfer_station().then((response) => {
			this.transferAllList = response.data;
		});
		// 执法记录仪
		allListDevices({type:'3'}).then(res => {
		  this.listAllVehicleTerminal = res.data
		})
	},
	// 收运公司列表
	listAllRecycling_company(){
		listAllRecycling_company().then(res => {
			this.companyList = res.data
		})
	},
	// 根据选择得收运公司列表获取司机列表
	companySelect(id){
		// this.form.driverId = ''
		// this.form.recyclerId =''
		// this.form.vehicleType = ''
		// this.form.receivingVehicleId = ''
		// this.receivingList = []
		// this.driverList2 = []
		// this.listAll_driver(id)
		// this.listAll_driver2(id)
	},
	// 司机列表 recyclingCompanyId 收运公司id   workType 所属工种 收运司机1  收运工 2
	// listAll_driver(id){
	// 	listAll_driver({
	// 		recyclingCompanyId:this.form.recyclingCompanyId,
	// 		workType:1,
	// 	}).then(res => {
	// 		this.driverList = res.data
	// 	})
	// },
	// 选择司机
	selectDriver() {
	  if (!this.form.collectionTime) {
		uni.$u.toast('请先选择收运时间');
		return;
	  }
	  this.getDriveList()
	  this.driveShow = true
	},
	getDriveList(){
		selectDriverTaskCount({
			pageNum: 1,
			pageSize: 50,
			taskType: 0, // 0收运 1运输
			time: this.form.collectionTime,
			recyclingCompanyId: this.form.recyclingCompanyId,
		}).then((res) => {
			this.driverData = res.data.records;
		});
	},
	// 选择司机
	driveConfirm(item){
		this.form.driverId = item.id;
		this.form.driverName = item.name;
		this.driveShow = false
	},
	// 收运工
	listAll_driver2(id){
		listAll_driver({
			recyclingCompanyId:this.form.recyclingCompanyId,
			workType:2,
		}).then(res => {
			this.driverList2 = res.data
		})
	},
	// 根据选择车辆得类型获取车辆列表
	vehicleSelect(id){
		console.log(id);
		this.form.receivingVehicleId = ''
		this.listAll_receiving_vehicle(id)
	},
	// 车辆列表 车辆类型 vehicleType
	listAll_receiving_vehicle(id){
		listAll_receiving_vehicle({
			vehicleType:id,
			recyclingCompanyId:this.form.recyclingCompanyId,
		}).then(res => {
			this.receivingList = res.data
		})
	},
    
	// 点击生成规划路线
	createPath() {
		this.pathList = {}
	  // 排放单位 [1,2,3]： emissionUnitIds，中转站id  ：transferStationId
	  let arr = [];
	  arr = this.form.orderVoList;
	  arr.sort((a, b) => a.orderSort - b.orderSort);
	  if (!this.form.recycleBinId) {
		uni.$u.toast('请您先选择中转站');
		return;
	  }
	  // this.isSort  是否是批量
	  if (
		this.form.orderVoList.length > 1 &&
		this.form.orderVoList.some((item) => !item.orderSort)
	  ) {
		uni.$u.toast('请您先排序');
		return;
	  }
	  // 起始点是收运公司，目的地是排放单位，终点是中转站
	  let emissionUnitIds = arr.map((item) => item.emissionUnitId);
	  let transferStationId = this.form.recycleBinId;
	  let recyclingCompanyId = this.form.recyclingCompanyId;
	  // origin 起点 destination 终点
	  planRoute({
		emissionUnitIds: emissionUnitIds,
		transferStationId: transferStationId,
		recyclingCompanyId: recyclingCompanyId
	  }).then((res) => {
		this.pathList = res.data.route;
		// let testStr = encodeURIComponent(JSON.stringify(this.pathList));
		let timeStamp = new Date().getTime();
		this.form.routingPic = ''
		// this.Mapview.webUrl.value = `/static/html/gMap.html?list=${this.pathList}&&${timeStamp}`;
	  });
	},
	
	submit(){
		this.$refs.uForm.validate().then((res) => {
		  dispatch(this.form).then(res => {
		  	uni.$u.toast('派单成功');
		  	this.goLink('','back')
		  })
		});
    },
	
	generatorImage(data) {
		  if (!this.pathList.origin) {
			uni.$u.toast('请先生成路线规划');
			return
		  }
		  if(data.path && !this.form.routingPic){
			console.log(data.path);
			uploadBase64({
				base64String: data.path,
			}).then((res) => {
				this.form.routingPic = res.url;
				// console.log(res.url);
				this.submit();
			});
		  }
		  if(this.form.routingPic){
			  this.submit()
		  }
	},
	
  },
};
</script>
<script module="render2" lang="renderjs">
	import html2Canvas from 'html2canvas'
	export default {
		data() {
			return {}
		},
		mounted() {},
		methods: {
			myprint() {
				this.$ownerInstance.callMethod('generatorImage');
				const detail = document.querySelector("#content2PDF") //获取到html包含此页面的外层标签，detail为页面中需要导出为pdf的最外层标签的id名
				const imgHeight = detail.clientHeight;
				const imgWidth = detail.clientWidth;
				html2Canvas(detail, { //对应的dom元素id(class也可以)
				    logging: true,
					allowTaint: true, //是否允许跨域图像渲染画布
					useCORS: true, //是否尝试使用 CORS 从服务器加载图像 解决图片跨域问题
				}).then((canvas) => {
					console.log('canvas',canvas);
					const base64 = canvas.toDataURL("image/png",1);
					this.$ownerInstance.callMethod('generatorImage', {
						path: base64,
					});
				});

			}
		},
	}
</script>
<style lang="less" scoped>
	.order-list{
		.item{
			padding: 20rpx;
			border-bottom: 1rpx solid #ccc;
			margin-bottom: 20rpx;
			.text{
				display: flex;
				align-items: center;
				margin-bottom: 20rpx;
				&:last-child{
					margin-bottom: 0;
				}
			}
		}
	}
.dispatch {
  padding: 30rpx 30rpx 0 30rpx;
  .title {
    font-size: 30rpx;
    color: #000;
    margin: 28rpx 0 20rpx 0;
    .delete {
      color: #138e57;
    }
  }
  .form {
    .form-item {
      padding: 0 30rpx;
      border-radius: 16rpx;
      margin: 20rpx 0;
      background: #ffffff;
    }
  }
  .button {
    margin: 0 40rpx;
    padding: 80rpx 0;
  }
  .button1 {
    color: #ffffff;
    margin-top: 30rpx;
    background: linear-gradient(83deg, #48b453 0%, #2c9f79 100%);
  }
  .button2 {
    color: #138e57;
    border: 2rpx solid #138e57;
  }
  .button1,
  .button2 {
    padding: 24rpx;
    text-align: center;
    border-radius: 200rpx;
    font-size: 32rpx;
  }
}

.drive-wrap{
	width: 80vw;
	max-height: 80vh;
	overflow: auto;
	padding: 30rpx;
	background: #f1f1f1;
	border-radius: 20rpx;
	.list{
		.item{
			background: #fff;
			margin-bottom: 20rpx;
			border-radius: 10rpx;
			padding: 20rpx;
			.name{}
			.text{
				display: flex;
				align-items: center;
				margin-top: 10rpx;
			}
		}
	}
}


</style>
